/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import React, {useEffect} from 'react';
import {Button, StyleSheet, View} from 'react-native';
import Swiper from 'react-native-swiper';
import Video from 'react-native-video';

import {AdaptiveRotation} from '@hadss/react_native_adaptive_video';
import {videoRotationList, VideoItem} from '../../components/videos';

const VideoSwiper = ({navigation}) => {
  useEffect(() => {
    AdaptiveRotation.getInstance().start();
    const firstVideo = videoRotationList[0];
    setNotFullScreen(firstVideo);
    return () => {
      AdaptiveRotation.getInstance().stop();
    };
  }, []);

  const onSwiperIndexChange = (index: number) => {
    const video = videoRotationList[index];
    setNotFullScreen(video);
  };

  const setNotFullScreen = (video: VideoItem) => {
    AdaptiveRotation.getInstance().setOrientationNotFullScreen({
      width: video.width,
      height: video.height,
    });
  };

  // 跳转到全屏页面
  const enterFullScreenPage = (video: VideoItem) => {
    navigation.navigate('Details', {id: video.id});
    AdaptiveRotation.getInstance().setOrientationFullScreen({
      width: video.width,
      height: video.height,
    });
  };

  return (
    <View style={{flex: 1}}>
      <Swiper
        loop={false}
        horizontal={false}
        showsPagination={false}
        onIndexChanged={onSwiperIndexChange}>
        {videoRotationList.map(video => (
          <View key={video.id} style={styles.slide}>
            <Video
              source={{uri: `assets://${video.source}`}}
              style={styles.video}
              resizeMode="contain"
              muted={true}
              repeat={true}
            />
            <Button
              title="进入全屏"
              onPress={() => {
                enterFullScreenPage(video);
              }}
            />
          </View>
        ))}
      </Swiper>
    </View>
  );
};

const styles = StyleSheet.create({
  slide: {
    width: '100%',
    height: '100%',
    justifyContent: 'center',
    alignItems: 'center',
  },
  video: {
    width: '100%',
    height: '90%',
    zIndex: 1,
  },
  button: {
    left: 50,
    top: 20,
    zIndex: 2,
  },
});

export default VideoSwiper;
